package com.piece.core.log.service;

import com.piece.core.log.client.AuditLogService;
import com.piece.core.log.client.dto.AuditLogDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 审计日志实现类
 */
@Slf4j
@Component("audit_log_service_logger")
@ConditionalOnProperty(name = "spring.log.type", havingValue = "logger")
public class AuditLogServiceLogger implements AuditLogService {

    /**
     * 日志格式：{时间}|{应用名}|{模块名}|{类名}|{方法名}|{请求参数}|{请求地址}|{租户id}|{操作用户id}|{操作用户名}|{访问ip}|{操作城市}|{操作地点}|{操作系统}|{浏览器}|{错误消息}
     */
    private static final String MSG_PATTERN = "{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}";

    @Async
    @Override
    public AuditLogDTO save(AuditLogDTO auditLog) {
        log.info(MSG_PATTERN
                , "请求时间=" + LocalDateTime.ofInstant(auditLog.getOperaTime().toInstant(), ZoneId.of("UTC")).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))
                , "应用名=" + auditLog.getApplicationName()
                , "模块名=" + auditLog.getModuleName()
                , "类名=" + auditLog.getClassName()
                , "方法名=" + auditLog.getMethodName()
                , "请求参数=" + auditLog.getOperaParam()
                , "请求地址=" + auditLog.getOperaUrl()
                , "租户ID=" + auditLog.getClientId()
                , "操作用户ID=" + auditLog.getOperaId()
                , "操作用户名=" + auditLog.getOperaName()
                , "访问ip=" + auditLog.getIp()
                , "操作城市=" + auditLog.getCity()
                , "操作地点=" + auditLog.getArea()
                , "操作系统=" + auditLog.getOs()
                , "浏览器=" + auditLog.getBrowser()
                , "错误消息=" + (auditLog.getStatus().equals("1") ? auditLog.getDesc() : ""));

        return auditLog;
    }

    @Override
    public void delete(AuditLogDTO audit) {
    }

    @Override
    public void deleteByClientId(String clientId) {
    }

    @Override
    public void clear() {
    }

    @Override
    public List<AuditLogDTO> findByCondition(Map<String, Object> param) {
        return Collections.emptyList();
    }
}